﻿import QtQuick 2.0
import QtQuick.Window 2.12
import "../dataAnalysis"
import "../components"
import "../program"

Item {

    id: pageExperiment

    // 属性状态控制 ========================================================
    property int gPageModel: 0          // 0:闲逛模式  1:新建实验模式
    property int gDeviceStep: 0         // 模式0时，Step页显示步骤    // Step - 0:实验信息 1:样本信息 2:运行 3:实验结果
    property int gNewStep: 0            // 模式1时，Step页显示步骤

    property bool gIsEditAmplProgram: false // 是否查看扩增程序

    property var gDeviceIdList: []      // 设备列表 - Id - List
    property var gDeviceInfoList: []    // 设备信息Map
    property var gDeviceStepList: {     // 缓存每个设备所处的Step页面
        "ffff": 1
    }
    property int gDeviceFilter: 5       // 设备筛选  0:离线 1:空闲 2:运行中 3:已完成 4:故障 5:全部

    // 空闲时设备的状态
    property string gCurDeviceId: ""    // 模式0时设备当前所选设备
    property int   gCurDeviceStatus: 0  // 模式0时当前所选设备的状态  0: 未连接 1: 空闲 2: 运行 3: 结束

    // 新建实验时设备的状态
    property string gCurNewId: ""       // 模式1时当前所选设备


    // 设备数量统计（用于筛选）
    property int gCountAll: 0
    property int gCountEmpty: 0
    property int gCountRunning: 0
    property int gCountFinish: 0
    property int gCountFault: 0
    property int gCountAvailable: gCountEmpty + gCountFinish
    property int gCountOffline: 0

    // ComboBox的默认选项
    property var gComboModel_sampleName: []
    property var gComboModel_sampleType: []
    property var gComboModel_kit:        []
    property var gComboModel_system:     []
    property var gComboModel_program:    []
    property var gComboModel_consume:    []
    // 默认选项的默认选项
    property int gDefaultIdx_sampleName: 0
    property int gDefaultIdx_sampleType: 0
    property int gDefaultIdx_kit:        0
    property int gDefaultIdx_system:     0
    property int gDefaultIdx_program:    0
    property int gDefaultIdx_consume:    0

    // 新建实验时，实验信息的存储
    property var gExperimentInfo: ({   "ExperimentName": "",
                                       "Code": "",
                                       "System": "",
                                       "ConsumableType": "",
                                       "TestKit": ""
                                     })
    property var  gSampleList: []

    property bool gIsNewRefresh_expInfo:     false       // 切入到新建实验时，是否清空之前的状态
    property bool gIsNewRefresh_sample:      false
    property bool gIsNewOpenRefresh_expInfo: false
    property bool gIsNewOpenRefresh_sample:  false

    property bool hasInit: false

    Connections{
        target: mainwindow
        onTabExperiment:{

            if(!hasInit){
                CRunningChart.load()
                CRunningChartBar.load()
                hasInit = true
            }
            refresh()
        }
        onAskForTab:{
            if(mainwindow.mainPage !== 1) return
            if(gPageModel === 1 && mainwindow.targetPage!==1){
                boxwarning_tabPage.show()
            }else{
                permitTab()
            }
        }
    }

    Connections{
        target: CSignal
        onExperimentEnd: {       // 实验结束 (QString equId)
            gDeviceStepList[equId] = 3
            if(gCurDeviceId === equId){
                gDeviceStep = 3
            }
            refresh()
        }
        onExperimentInterruption: { // 设备连接异常中断 Param(QString equId)
            refresh()
        }
        onStartExperimentStatus: {
            if(status.toString() === "0"){
                mainwindow.showToast("实验启动失败", 1)
                return
            }else if(status.toString() === "2"){       // 用户取消新建
                return
            }else if(status.toString() === "3"){
                mainwindow.showToast("保存成功", 0)
                return
            }

            // 跳转回来
            mainwindow.showToast("实验启动成功", 0)

            if(gPageModel === 1){           // 非一键启动时，将当前设备定位到新建实验的设备
                gCurDeviceId = gCurNewId
            }
            gPageModel = 0
            gCurDeviceStatus = 2
            gDeviceStepList[gCurDeviceId] = 2
            gDeviceStep = 2
            gDeviceFilter = 5

            // 清空之前的数据分析结果
            CAnalysis.closeAnalysis(gCurDeviceId)
            startExperimentSuccess(gCurDeviceId)    // 发送实验启动成功信号
            refresh()
        }
    }

    signal reanalysis()
    signal startExperimentSuccess(var equId)

    // 设备还得存一个状态，存储之前的设备在哪个页面


    // 弹窗 ===============================================================
    BoxNewExperiment{
        id: boxNewExperiment
        onAccept: {
            oneStartExperiment()
        }onReject: {

        }
    }
    BoxAmplProgram{
        id: boxAmplProgram
    }


    BoxWarning{
        id: boxwarning_stopExperiment
        box_text: "确认停止实验吗?"
        onAccept: {
            gCurDeviceStatus = 3
            gDeviceStep = 3
            gDeviceStepList[gCurDeviceId] = 3
            CExpPro.stopExperiment(gCurDeviceId)
            refresh()
        }
    }
    BoxWarning{
        id: boxwarning_tabPage
        box_text: "当前页面有未保存数据，确认切换吗？"
        onAccept: {
            gPageModel = 0
            mainwindow.permitTab()
        }
    }
    BoxWarning{
        id: boxwarning_noAmplProgram
        box_text: "请先创建扩增程序"
        onAccept: {
            mainwindow.mainPage = 4
            mainwindow.tabProgram(-1)
        }
    }



    function refresh(){
        // 信息处理
        refreshComboModel()
        refreshDeviceList()

        // 下发刷新
        experimentLayout.refresh()
    }

    // 状态控制函数 ============================================================
    function refreshComboModel(){
        var list = []
        let i = 0

        gComboModel_sampleName  = []
        list = CSetUp.refTableData("样本名称")
        for(i = 0; i < list.length; i ++){
            gComboModel_sampleName.push(list[i][1])
        }
        gComboModel_sampleType  = []
        list = CSetUp.refTableData("样本类型")
        for(i = 0; i < list.length; i ++){
            gComboModel_sampleType.push(list[i][1])
        }
        gComboModel_kit  = []
        list = CSetUp.refTableData("试剂盒")
        for(i = 0; i < list.length; i ++){
            gComboModel_kit.push(list[i][1])
        }
        gComboModel_system  = []
        list = CSetUp.refTableData("扩增体系(μl)")
        for(i = 0; i < list.length; i ++){
            gComboModel_system.push(list[i][1])
        }
        gComboModel_consume  = []
        list = CSetUp.refTableData("耗材类型")
        for(i = 0; i < list.length; i ++){
            gComboModel_consume.push(list[i][1])
        }

        list = CAmplProgram.getProgramInfo(0)
        gComboModel_program = []
        gDefaultIdx_program = 0
        for(i = 0; i < list.length; i ++){
            gComboModel_program.push(list[i]["ProgramName"])
            if(list[i]["IsDefault"].toString()==="1"){
                gDefaultIdx_program = i;
            }
        }
    }


    // 状态改变
    function changeCurId(cid){      // 改变当前指向的设备
        if(gPageModel === 0){
            gCurDeviceId = cid
            gDeviceStep = gDeviceStepList[gCurDeviceId]
            gCurDeviceStatus = gDeviceInfoList[gCurDeviceId]["EquStatus"]
            refresh()
        }else if(gPageModel === 1){
            gCurNewId = cid
            refresh()
        }
    }
    function changeDeviceFilter(type){  // 改变当前筛选
        gDeviceFilter = type
        refresh()
    }

    // 切换当前设备的页面
    function changeStepPage(idx){
        if(gPageModel === 0){
            gDeviceStepList[gCurDeviceId] = idx
            gDeviceStep = idx
        }else{
            gNewStep = idx
        }
        refresh()

    }


    // 按钮点击事件
    function onButtonOneStart(){
        boxNewExperiment.show()
    }

    // 打开实验
    function onButtonOpenExp(){
        let res = CWlk.openWlkFile_getInfo()
        if(res["Res"] === undefined || res["Res"] === 2){
            return
        }else if(res["Res"].toString() === "0"){
            mainwindow.showToast("文件格式错误", 1)
            return
        }

        gExperimentInfo = res["ExpInfo"]
        gSampleList = res["SampleInfo"]

        gPageModel = 1
        gNewStep = 0
        // 当前设备可启动实验时，gCurNewId为当前设备Id
        if(gDeviceInfoList[gCurDeviceId]["EquStatus"].toString() === "1" || gDeviceInfoList[gCurDeviceId]["EquStatus"].toString() === "3"){
            gCurNewId = gCurDeviceId
        }
        // 当前设备不可启动实验时，gCurNewId为第一个可用的设备
        else{
            gCurNewId = gCurDeviceId
            for(let key in gDeviceInfoList){
                if(gDeviceInfoList[key]["EquStatus"].toString() === "1" || gDeviceInfoList[key]["EquStatus"].toString() === "3"){
                    gCurNewId = key
                    break
                }
            }
        }
        gIsNewOpenRefresh_expInfo = true
        gIsNewOpenRefresh_sample = true

        refresh()
    }
    // 新建实验
    function onButtonNewExp(){
        gPageModel = 1
        gNewStep = 0
        // 当前设备可启动实验时，gCurNewId为当前设备Id
        if(gDeviceInfoList[gCurDeviceId]["EquStatus"].toString() === "1" || gDeviceInfoList[gCurDeviceId]["EquStatus"].toString() === "3"){
            gCurNewId = gCurDeviceId
        }
        // 当前设备不可启动实验时，gCurNewId为第一个可用的设备
        else{
            gCurNewId = gCurDeviceId
            for(let key in gDeviceInfoList){
                if(gDeviceInfoList[key]["EquStatus"].toString() === "1" || gDeviceInfoList[key]["EquStatus"].toString() === "3"){
                    gCurNewId = key
                    break
                }
            }
        }
        gIsNewRefresh_expInfo = true
        gIsNewRefresh_sample = true
        refresh()
    }

    // 返回 (新建实验)
    function onButtonBack(){
        gPageModel = 0
        refresh()
    }
    function onButtonDeviceManager(){  // 跳转到设备管理页面
        mainwindow.mainPage = 6
        mainwindow.tabSettings()
    }


    function onButtonExportReport(){
        var res = CAnalysis.datao()
        if(res === 1){
            mainwindow.showToast("导出成功", 0)
        }else if(res === 0){
            mainwindow.showToast("导出失败", 1)
        }
    }
    function onButtonExportImage(){
        var res = CAnalysis.exportImage()
        if(res === 1){
            mainwindow.showToast("导出成功", 0)
        }else if(res === 0){
            mainwindow.showToast("导出失败", 1)
        }
    }
    function onButtonReAnalysis(){
        pageExperiment.reanalysis()
    }
    function onButtonCheckAmplProgram(){        // 查看扩增程序 - 弹窗
        boxAmplProgram.show()
        boxAmplProgram.setEquId(gCurDeviceId)      // [TODO] 后端接口
    }

    function editAmplProgram(programName){            // 查看扩增程序 - 可修改
        gIsEditAmplProgram = true
        editProgram.setProgram(programName)
    }

    function refreshDeviceList(){
        // 获取设备列表

        gDeviceInfoList = CSetUp.queryEquInfoConnect()

        gDeviceIdList = []
        for(let key in gDeviceInfoList){
            gDeviceIdList.push(key)
        }
        if(gDeviceIdList.length === 0){                // 设备列表为空
            gCurDeviceId = ""
//            return
        }else if(gDeviceIdList.indexOf(gCurDeviceId) === -1){     // 判断当前显示的Id是否还存在，若不存在则显示列表中第一个设备
            gCurDeviceId = gDeviceIdList[0]
        }
        // 更新当前设备所在的页面
        // 1. 删除了的设备，删除Map所在元素
        // 2. 新增加的设备页面置于1
        for(let key in gDeviceStepList){
            if(gDeviceIdList.indexOf(key) === -1){
                delete gDeviceStepList[key]
            }
        }for(let i = 0; i < gDeviceIdList.length; i ++){
            if(!(gDeviceStepList[gDeviceIdList[i]] !== undefined)){
                gDeviceStepList[gDeviceIdList[i]] = 0
            }
        }

        // 记录设备状态数量
        var equNumList = CSetUp.queryEquNum()
        gCountOffline = equNumList[1]
        gCountEmpty = equNumList[2]
        gCountRunning = equNumList[3]
        gCountFinish = equNumList[4]
        gCountFault = equNumList[5]

        gCountAll = gDeviceIdList.length

        if(equNumList[gDeviceFilter] === 0){        // 如果筛选列表空了，跳到第一个筛选列表
            gDeviceFilter = 5
        }

        if(gCurDeviceId!==""){
            gCurDeviceStatus = gDeviceInfoList[gCurDeviceId]["EquStatus"]
        }

    }

    function onButtonSave(){
        gExperimentInfo["EquId"] = gCurNewId
        if(gExperimentInfo["AmplGuid"] === "" || gExperimentInfo["ExperimentName"] === ""){
            mainwindow.showToast("请完整填写实验信息", 1)
            return
        }
        CExpInfo.startExperiment(gExperimentInfo, gSampleList, 1)
    }

    function startExperiment(){
        // 信息校验
        gExperimentInfo["EquId"] = gCurNewId
        if(gExperimentInfo["AmplGuid"] === "" || gExperimentInfo["ExperimentName"] === ""){
            mainwindow.showToast("请完整填写实验信息", 1)
            return
        }

        // 向后端发送指令
        CExpInfo.startExperiment(gExperimentInfo, gSampleList, 0)


    }


    function oneStartExperiment(){
        gExperimentInfo["EquId"] = gCurDeviceId
        CExpInfo.onePointStartExperiment(gExperimentInfo)

    }

    function stopExperiment(){
        boxwarning_stopExperiment.show()
    }

    // 布局 ==================================================================

    anchors.fill: parent

    // 实验
    ExperimentLayout{
        id: experimentLayout
        visible: !gIsEditAmplProgram
    }
    EditProgram{        // 查看扩增程序
        id: editProgram
        visible: gIsEditAmplProgram
    }

}
